#import "SolarSeekMessageWriter.h"

@implementation SolarSeekMessageWriter
@synthesize delegate;
@synthesize stream;
@synthesize autoOpenStream;

-(void) setStream:(NSOutputStream *)i {
  if (stream) {
    [stream close];
    [stream setDelegate:nil];
    [stream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
  }
  
  stream = i;
  
  if (autoOpenStream)
    [self open];
  
}

-(void) open {
  if (stream) {
    [stream setDelegate:self];
    [stream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [stream open];
  }
}  

-(void) disconnect {
  self.stream = nil;
  
  if ([delegate respondsToSelector:@selector(disconnect)])
    [delegate performSelector:@selector(disconnect)];
}

+(SolarSeekMessageWriter *) writerWithStream:(NSOutputStream *)stream andDelegate:(id)delegate {
  SolarSeekMessageWriter *writer = [[self alloc] init];
  writer.delegate = delegate;
  writer.stream = stream;
  return writer;
}

-(void)sendMessages {
	if (stream && [stream hasSpaceAvailable] && ([queue count] > 0)) {
		MuseekMessage *message = [queue objectAtIndex:0];
		[queue removeObjectAtIndex:0];
		
    // BUG : Only works for small messages. Big messages need a loop, like the one in MessageReader
		[stream write:[message bytes] 
				maxLength:[message length]];
    
    if ([delegate respondsToSelector:@selector(messageSent:)])
      [delegate performSelector:@selector(messageSent:) withObject:message];

    // I really don't think the line below is necessary. NSStream would inform me when the stream is available again.
//    [self performSelector:@selector(sendMessages) withObject:nil afterDelay:0.0f];	
  }
}


-(void) stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
	if ((eventCode == NSStreamEventEndEncountered) || (eventCode == NSStreamEventErrorOccurred)) {
		[self disconnect];
	}
	
	if (eventCode == NSStreamEventHasSpaceAvailable) 
		[self sendMessages];
}

- (id) init {
  self = [super init];
  if (self != nil) {
    stream = nil;
    delegate = nil;
    autoOpenStream = YES;
		queue = [[NSMutableArray alloc] init];
  }
  return self;
}

-(void) send:(MuseekMessage *)message {
  [queue addObject:message];
  [self sendMessages];
}

@end
